
package com.tools.cleanmaster.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Process;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;

import com.tools.cleanmaster.CleanApplication;

import java.io.Closeable;
import java.io.IOException;
import java.lang.reflect.Field;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Iterator;
import java.util.List;

public class Utils {
    static final String LOG_TAG = "Utils";
    private static int sScreenWidth = 0;
    private static int sScreenHeight = 0;

    /**
     * util
     * A hashing method that changes a string (like a URL) into a hash suitable
     * for using as a disk filename.
     */
    public static String hashKeyForDisk(String key) {
        return md5ForString(key);
    }

    /**
     * Get md5 of a string.
     *
     * @param content
     * @return hasCode of string if there is no MD5 algorithm.
     */
    public static String md5ForString(String content) {
        String result;
        try {
            final MessageDigest mDigest = MessageDigest.getInstance("MD5");
            mDigest.update(content.getBytes());
            result = bytesToHexString(mDigest.digest());
        } catch (NoSuchAlgorithmException e) {
            result = String.valueOf(content.hashCode());
        }
        return result;
    }

    public static String bytesToHexString(byte[] bytes) {
        // http://stackoverflow.com/questions/332079
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(0xFF & bytes[i]);
            if (hex.length() == 1) {
                sb.append('0');
            }
            sb.append(hex);
        }
        return sb.toString();
    }

    public static void closeQuietly(Closeable closeable) {
        if (closeable == null) {
            return;
        }
        try {
            closeable.close();
        } catch (IOException e) {
            // empty
        }
    }

    @SuppressLint("NewApi")
    @SuppressWarnings("deprecation")
    public static void destroyActivityViews(Activity activity) {
        if (activity == null) {
            return;
        }
        try {
            View win = activity.findViewById(android.R.id.content);
            destroyView(win);
            View decorView = activity.getWindow().getDecorView();
            if (decorView != null) {
                if (Build.VERSION.SDK_INT >= 16) {
                    //                     decorView.setBackground(null);
                } else {
                    decorView.setBackgroundDrawable(null);
                }
            }
        } catch (Throwable t) {
        }
    }

    public static void destroyView(View view) {
        if (view == null) {
            return;
        }

        // set view.mContext = null, mParent = null
        try {
            ClassLoader cl = ClassLoader.getSystemClassLoader();
            Class<?> clsView;
            clsView = cl.loadClass("android.view.View");

            Field fieldParent = clsView.getDeclaredField("mParent");
            fieldParent.setAccessible(true);
            fieldParent.set(view, null);
        } catch (ClassNotFoundException e) {
        } catch (SecurityException e) {
        } catch (IllegalArgumentException e) {
        } catch (IllegalAccessException e) {
        } catch (NoSuchFieldException e) {
        } catch (NullPointerException e) {
        }

        try {
            view.setVisibility(View.GONE);
            view.destroyDrawingCache();

            if (view.getBackground() != null) {
                view.setBackgroundDrawable(null);
            }

            view.setAnimation(null);
            view.setOnFocusChangeListener(null);
            view.setOnKeyListener(null);
            view.setOnLongClickListener(null);
            view.setOnTouchListener(null);
            if (!(view instanceof AdapterView)) {
                view.setOnClickListener(null);
            }

            if ((view instanceof ViewGroup) && !(view instanceof AdapterView)) {
                ViewGroup vg = (ViewGroup) view;
                int count = vg.getChildCount();
                for (int i = 0; i < count; i++) {
                    View v = vg.getChildAt(i);
                    if (v != null) {
                        destroyView(v);
                    }
                }
                vg.removeAllViews();
            } else if (view instanceof AdapterView) {
                AdapterView<?> av = (AdapterView<?>) view;
                av.setAdapter(null);
                av.setAnimation(null);
                av.setOnItemClickListener(null);
                av.setOnItemSelectedListener(null);
                av.setOnItemLongClickListener(null);
            }
        } catch (Exception e) {
            // silently discard all errors
        }
    }

    public static int dipToPx(Context context, int dip) {
        return (int) (dip * getDensity(context) + 0.5f);
    }

    public static float getDensity(Context context) {
        DisplayMetrics dm = new DisplayMetrics();
        ((WindowManager) context.getApplicationContext().getSystemService(Context.WINDOW_SERVICE))
                .getDefaultDisplay().getMetrics(dm);
        return dm.density;
    }

    public static boolean isMDPI() {
        Resources res = Resources.getSystem();
        DisplayMetrics met = res.getDisplayMetrics();
        return met.densityDpi <= DisplayMetrics.DENSITY_MEDIUM;
    }

    public static int getScreenWidthPixels() {
        if (sScreenWidth == 0) {
            DisplayMetrics dm = new DisplayMetrics();
            ((WindowManager) CleanApplication.getInstance().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay()
                    .getMetrics(dm);
            sScreenWidth = dm.widthPixels;
            sScreenHeight = dm.heightPixels;
        }
        return sScreenWidth;
    }

    public static int getScreenHeightPixels() {
        if (sScreenHeight == 0) {
            DisplayMetrics dm = new DisplayMetrics();
            ((WindowManager) CleanApplication.getInstance().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay()
                    .getMetrics(dm);
            sScreenWidth = dm.widthPixels;
            sScreenHeight = dm.heightPixels;
        }
        return sScreenHeight;
    }

    public static int px2dip(Context context, float pxValue) {
        if (context == null || pxValue <= 0) {
            return 0;
        }

        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    private static int DENSITY = 0;

    public static int dip2px(Context context, float dpValue) {
        if (context == null || dpValue <= 0) {
            return 0;
        }

        if (DENSITY == 0) {
            DENSITY = (int) context.getResources().getDisplayMetrics().density;
        }
        return (int) (dpValue * DENSITY + 0.5f);
    }

    public static String getProcessName(Context cxt) {
        int pid = Process.myPid();
        ActivityManager am = (ActivityManager) cxt.getSystemService("activity");
        if (am == null) {
            return null;
        } else {
            List runningApps = am.getRunningAppProcesses();
            if (runningApps == null) {
                return null;
            } else {
                Iterator var4 = runningApps.iterator();

                ActivityManager.RunningAppProcessInfo procInfo;
                do {
                    if (!var4.hasNext()) {
                        return null;
                    }

                    procInfo = (ActivityManager.RunningAppProcessInfo) var4.next();
                } while (procInfo.pid != pid);

                return procInfo.processName;
            }
        }
    }

    public static boolean isRemoteProcess(Context ctx) {
        try {
            String processName = getProcessName(ctx);
            if (processName != null) {
                int idx = processName.lastIndexOf(":");
                if (idx != -1) {
                    processName = processName.substring(idx + 1);
                }
            }
            return "remote".equals(processName);
        } catch (Exception e) {
            if (FeatureConfig.DEBUG_LOG) {
                e.printStackTrace();
            }
        }
        return false;
    }

    public static boolean isMainProcess(Context ctx) {
        try {
            String processName = getProcessName(ctx);
            return ctx.getPackageName().equals(processName);
        } catch (Exception e) {
            if (FeatureConfig.DEBUG_LOG) {
                e.printStackTrace();
            }
        }
        return false;
    }

    public static Bitmap decodeSampledBitmapFromResource(Resources resources, int cpu_cool_down_snow, int i, int i1) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.outWidth = i;
        options.outHeight = i1;
        return BitmapFactory.decodeResource(resources, cpu_cool_down_snow, options);
    }
}
